package com.diao.myhub.util;

import com.diao.myhub.exception.CustomizeError;
import com.diao.myhub.exception.CustomizeException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class FileUtils {
    public static String uploadToServer(MultipartFile file, String path) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String date = format.format(new Date());
        String realPath = path + File.separator + date + File.separator;
        File dir = new File(realPath);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                return null;
            }
        }
        // 处理上传文件文件名
        String filename = file.getOriginalFilename();
        if (filename == null) {
            return "null";
        }
        String fileExt;
        if (filename.lastIndexOf('.') != -1) {
            fileExt = filename.substring(filename.lastIndexOf('.'));
        } else {
            throw new CustomizeException(CustomizeError.FILE_TYPE_ERROR);
        }
        String realName = UUID.randomUUID().toString().replace("-", "") + fileExt;
        try {
            file.transferTo(new File(realPath + realName));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        // 文件访问url,对与prodL1环境，这个文件被映射到H盘jar包所在路径下的imgs文件夹
        return "/uploadFiles/" + date + "/" + realName;
    }
}
